<template>
  <div class="profile-page">
    <div class="user-header">
      <div class="avatar-wrapper">
        <van-image
          round
          width="80"
          height="80"
          src="https://fastly.jsdelivr.net/npm/@vant/assets/cat.jpeg"
          alt="用户头像"
        />
        <div class="avatar-edit" @click="showUploadPopup">
          <van-icon name="photograph" />
        </div>
      </div>
      <div class="user-name">{{ userData.username }}</div>
      <div class="user-role">
        {{ userData.role === "admin" ? "管理员" : "普通用户" }}
      </div>
    </div>

    <div class="card-list">
      <!-- 个人信息卡片 -->
      <div class="profile-card">
        <div class="card-title">个人信息</div>
        <van-cell-group inset>
          <van-cell title="用户名" :value="userData.username" />
          <van-cell title="手机号" :value="userData.phone || '未绑定'" />
          <van-cell
            title="注册时间"
            :value="formatDate(userData.create_time)"
          />
          <van-cell title="修改密码" is-link @click="showPasswordPopup" />
        </van-cell-group>
      </div>

      <!-- 设置卡片 -->
      <div class="settings-card">
        <div class="card-title">设置</div>
        <van-cell-group inset>
          <van-cell title="消息通知" center>
            <template #right-icon>
              <van-switch v-model="settings.notifications" size="24" />
            </template>
          </van-cell>
          <van-cell title="显示分数" center>
            <template #right-icon>
              <van-switch v-model="settings.showScores" size="24" />
            </template>
          </van-cell>
          <van-cell title="隐私设置" is-link @click="showToast('暂未开放')" />
          <van-cell title="关于我们" is-link @click="showToast('暂未开放')" />
        </van-cell-group>
      </div>
    </div>

    <!-- 退出按钮 -->
    <div class="logout-btn">
      <van-button type="danger" block @click="handleLogout"
        >退出登录</van-button
      >
    </div>

    <!-- 修改密码弹窗 -->
    <van-popup
      v-model:show="showPassword"
      position="bottom"
      round
      class="password-popup"
    >
      <div class="popup-container">
        <div class="popup-header">
          <div class="popup-title">修改密码</div>
          <van-icon
            name="cross"
            @click="showPassword = false"
            class="popup-close"
          />
        </div>

        <van-form @submit="onPasswordSubmit">
          <van-cell-group inset>
            <van-field
              v-model="passwordForm.oldPassword"
              type="password"
              name="oldPassword"
              label="当前密码"
              placeholder="请输入当前密码"
              :rules="[{ required: true, message: '请输入当前密码' }]"
            />
            <van-field
              v-model="passwordForm.newPassword"
              type="password"
              name="newPassword"
              label="新密码"
              placeholder="请输入新密码"
              :rules="[
                { required: true, message: '请输入新密码' },
                {
                  validator: validateNewPassword,
                  message: '密码不能少于6个字符',
                },
              ]"
            />
            <van-field
              v-model="passwordForm.confirmPassword"
              type="password"
              name="confirmPassword"
              label="确认新密码"
              placeholder="请再次输入新密码"
              :rules="[
                { required: true, message: '请确认新密码' },
                {
                  validator: validateConfirmPassword,
                  message: '两次输入的密码不一致',
                },
              ]"
            />
          </van-cell-group>

          <div style="margin: 16px">
            <van-button
              round
              block
              type="primary"
              native-type="submit"
              :loading="loading"
            >
              确认修改
            </van-button>
          </div>
        </van-form>
      </div>
    </van-popup>

    <!-- 上传头像弹窗 -->
    <van-popup
      v-model:show="showUpload"
      position="bottom"
      round
      class="upload-popup"
    >
      <div class="popup-container">
        <div class="popup-header">
          <div class="popup-title">修改头像</div>
          <van-icon
            name="cross"
            @click="showUpload = false"
            class="popup-close"
          />
        </div>

        <div class="upload-buttons">
          <van-button
            icon="photograph"
            type="primary"
            block
            @click="showToast('暂未开放上传功能')"
          >
            从相册选择
          </van-button>
          <van-button
            icon="photo-o"
            plain
            type="primary"
            block
            style="margin-top: 12px"
            @click="showToast('暂未开放拍照功能')"
          >
            拍照
          </van-button>
        </div>
      </div>
    </van-popup>

    <!-- 底部导航 -->
    <van-tabbar route>
      <van-tabbar-item icon="home-o" to="/home">首页</van-tabbar-item>
      <van-tabbar-item icon="notes-o" to="/history">历史</van-tabbar-item>
      <van-tabbar-item icon="user-o" to="/profile">我的</van-tabbar-item>
    </van-tabbar>
  </div>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref } from "vue";

import { showDialog, showToast } from "vant";
import { useRouter } from "vue-router";

import { authApi } from "../../api/modules/auth";
import { useUserStore } from "../../stores/user";

const router = useRouter();
const userStore = useUserStore();

const loading = ref(false);
const showPassword = ref(false);
const showUpload = ref(false);

// 用户数据
const userData = reactive({
  username: "",
  phone: "",
  role: "",
  create_time: "",
});

// 应用设置
const settings = reactive({
  notifications: true,
  showScores: true,
});

// 密码表单
const passwordForm = reactive({
  oldPassword: "",
  newPassword: "",
  confirmPassword: "",
});

// 验证确认密码
const validateConfirmPassword = () => {
  return passwordForm.newPassword === passwordForm.confirmPassword;
};

// 验证新密码长度
const validateNewPassword = (val: string) => {
  return val.length >= 6;
};

// 获取用户信息
onMounted(async () => {
  // showToast({
  //   message: "加载中...",
  // });
  if (!userStore.user) {
    try {
      await userStore.getUserInfo();
    } catch (error) {
      console.error("获取用户信息失败", error);
      return;
    }
  }

  if (userStore.user) {
    userData.username = userStore.user.username || "";
    userData.phone = userStore.user.phone || "";
    userData.role = userStore.user.role || "";
    userData.create_time = userStore.user.create_time || "";
  }
});

// 格式化日期
const formatDate = (dateStr: string) => {
  if (!dateStr) return "未知";

  const date = new Date(dateStr);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, "0");
  const day = String(date.getDate()).padStart(2, "0");

  return `${year}-${month}-${day}`;
};

// 提交密码修改
const onPasswordSubmit = async () => {
  if (passwordForm.newPassword !== passwordForm.confirmPassword) {
    showToast("两次输入的密码不一致");
    return;
  }

  loading.value = true;
  try {
    await authApi.changePassword({
      oldPassword: passwordForm.oldPassword,
      newPassword: passwordForm.newPassword,
    });

    showToast("密码修改成功");
    showPassword.value = false;

    // 清空表单
    passwordForm.oldPassword = "";
    passwordForm.newPassword = "";
    passwordForm.confirmPassword = "";
  } catch (error) {
    console.error("修改密码失败", error);
  } finally {
    loading.value = false;
  }
};

// 显示密码修改弹窗
const showPasswordPopup = () => {
  showPassword.value = true;
};

// 显示头像上传弹窗
const showUploadPopup = () => {
  showUpload.value = true;
};

// 退出登录
const handleLogout = async () => {
  try {
    await showDialog({
      title: "确认退出",
      message: "确定要退出登录吗？",
      confirmButtonText: "确认退出",
      cancelButtonText: "取消",
    });

    await userStore.logout();
    router.replace("/login");
  } catch (error) {
    // 用户取消操作
  }
};
</script>

<style scoped>
/* 确保页面在所有设备上都能正常滚动 */
.profile-page {
  min-height: 100vh;
  background-color: #f5f7fa;
  padding-bottom: 80px; /* 增加底部间距，确保退出按钮可见 */
  overflow-y: auto; /* 确保可以滚动 */
  /* 优化移动端滚动性能 */
  -webkit-overflow-scrolling: touch;
  scroll-behavior: smooth;
}

/* 针对不同屏幕高度的适配 */
@media (max-height: 800px) {
  .profile-page {
    padding-bottom: 100px;
  }
}

@media (max-height: 700px) {
  .profile-page {
    padding-bottom: 120px;
  }

  .user-header {
    padding: 20px 0;
  }
}

@media (max-height: 600px) {
  .profile-page {
    padding-bottom: 140px;
  }

  .user-header {
    padding: 15px 0;
  }

  .card-list {
    padding: 12px;
  }

  .profile-card,
  .settings-card {
    margin-bottom: 10px;
  }
}

/* 超小屏幕高度适配 (iPhone SE 横屏等) */
@media (max-height: 500px) {
  .profile-page {
    padding-bottom: 160px;
  }

  .user-header {
    padding: 10px 0;
  }

  .avatar-wrapper :deep(.van-image) {
    width: 50px !important;
    height: 50px !important;
  }

  .user-name {
    font-size: 16px;
    margin-bottom: 2px;
  }

  .user-role {
    font-size: 12px;
  }

  .card-list {
    padding: 8px;
  }

  .card-title {
    font-size: 14px;
    margin: 0 12px 8px;
  }

  .logout-btn {
    margin-top: 12px;
    padding: 8px;
  }
}

.user-header {
  background-color: #1989fa;
  color: #fff;
  padding: 30px 0;
  text-align: center;
}

.avatar-wrapper {
  position: relative;
  display: inline-block;
  margin-bottom: 12px;
}

/* 小屏适配：头像尺寸调整 */
@media (max-width: 375px) {
  .avatar-wrapper :deep(.van-image) {
    width: 60px !important;
    height: 60px !important;
  }

  .avatar-edit {
    width: 20px;
    height: 20px;
  }

  .avatar-edit :deep(.van-icon) {
    font-size: 12px;
  }
}

.avatar-edit {
  position: absolute;
  bottom: 0;
  right: 0;
  width: 24px;
  height: 24px;
  background-color: #fff;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
}

.avatar-edit :deep(.van-icon) {
  color: #1989fa;
  font-size: 14px;
}

.user-name {
  font-size: 18px;
  font-weight: 600;
  margin-bottom: 4px;
}

/* 小屏适配：用户名字体调整 */
/* @media (max-width: 375px) {
  .user-name {
    font-size: 16px;
  }
} */

.user-role {
  font-size: 14px;
  opacity: 0.8;
}

/* 小屏适配：角色字体调整 */
/* @media (max-width: 375px) {
  .user-role {
    font-size: 12px;
  }
} */

.card-list {
  padding: 16px;
}

/* 小屏适配：减少卡片列表内边距 */
/* @media (max-width: 375px) {
  .card-list {
    padding: 12px;
  }
} */

.profile-card,
.settings-card {
  margin-bottom: 16px;
}

/* 小屏适配：减少卡片间距 */
/* @media (max-width: 375px) {
  .profile-card,
  .settings-card {
    margin-bottom: 12px;
  }
} */

.card-title {
  font-size: 16px;
  font-weight: 600;
  color: #323233;
  margin: 0 16px 12px;
}

/* 小屏适配：卡片标题调整 */
/* @media (max-width: 375px) {
  .card-title {
    font-size: 15px;
    margin: 0 12px 10px;
  }
} */

.logout-btn {
  padding: 16px;
  margin-top: 32px;
}

/* 小屏适配：退出按钮区域调整 */
/* @media (max-width: 375px) {
  .logout-btn {
    padding: 12px;
    margin-top: 20px;
  }
} */

.popup-container {
  padding: 20px 16px;
}

/* 小屏适配：弹窗容器调整 */
/* @media (max-width: 375px) {
  .popup-container {
    padding: 16px 12px;
  }
} */

.popup-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

/* 小屏适配：弹窗头部调整 */
/* @media (max-width: 375px) {
  .popup-header {
    margin-bottom: 16px;
  }
} */

.popup-title {
  font-size: 18px;
  font-weight: 600;
  color: #323233;
}

/* 小屏适配：弹窗标题调整 */
/* @media (max-width: 375px) {
  .popup-title {
    font-size: 16px;
  }
} */

.popup-close {
  font-size: 20px;
  color: #969799;
}

/* 小屏适配：关闭按钮调整 */
/* @media (max-width: 375px) {
  .popup-close {
    font-size: 18px;
  }
} */

.upload-buttons {
  padding: 20px 0;
}

/* 小屏适配：上传按钮区域调整 */
/* @media (max-width: 375px) {
  .upload-buttons {
    padding: 16px 0;
  }
} */

/* 密码弹窗响应式高度 */
.password-popup :deep(.van-popup) {
  height: auto;
  min-height: 50%;
  max-height: 80%;
}

/* 小屏适配：密码弹窗调整 */
/* @media (max-width: 375px) {
  .password-popup :deep(.van-popup) {
    min-height: 60%;
    max-height: 90%;
  }
} */

/* 上传弹窗响应式高度 */
.upload-popup :deep(.van-popup) {
  height: auto;
  min-height: 30%;
  max-height: 50%;
}

/* 小屏适配：上传弹窗调整 */
/* @media (max-width: 375px) {
  .upload-popup :deep(.van-popup) {
    min-height: 40%;
    max-height: 60%;
  }
} */

/* 表单区域在小屏下的优化 */
/* @media (max-width: 375px) {
  .popup-container :deep(.van-cell-group) {
    margin: 0 -8px;
  }

  .popup-container :deep(.van-field__label) {
    font-size: 14px;
    min-width: 80px;
  }

  .popup-container :deep(.van-field__control) {
    font-size: 14px;
  }

  .popup-container :deep(.van-button) {
    font-size: 14px;
    height: 40px;
  }
} */

/* 确保内容在小屏下不会被遮挡 */
/* @media (max-width: 375px) and (max-height: 667px) {
  .profile-page {
    padding-bottom: 100px; 
  }

  .user-header {
    padding: 15px 0;
  }

  .card-list {
    padding: 8px;
  }

  .logout-btn {
    margin-top: 16px;
    padding: 8px;
  }
} */

/* 超小屏适配 (iPhone SE 等) */
/* @media (max-width: 320px) {
  .user-header {
    padding: 12px 0;
  }

  .avatar-wrapper :deep(.van-image) {
    width: 50px !important;
    height: 50px !important;
  }

  .user-name {
    font-size: 14px;
  }

  .user-role {
    font-size: 11px;
  }

  .card-list {
    padding: 8px;
  }

  .card-title {
    font-size: 14px;
    margin: 0 8px 8px;
  }

  .popup-container {
    padding: 12px 8px;
  }

  .popup-title {
    font-size: 15px;
  }
} */
</style>
